package org.jlambda.util.math;

import org.jlambda.list.List;
import org.jlambda.listFunctions.ListFun1;

public class SievePrimes extends ListFun1<Long, Integer> {

	boolean sieve[] = null;
	
	int last = 1;//res.get(res.size()-1).longValue();
	@Override
	protected void create(List<Integer> list, Long hint) {
		// fill the seive
		sieve = new boolean[hint.intValue()];
		long max = (long) java.lang.Math.sqrt(hint.doubleValue());
		
		sieve[0] = false;
		sieve[1] = false;
		
		// add the list
		for (int i = 2; i < hint; i++) {
			sieve[i]=true;
		}
		
		for (int i=2; i<max; i++){
			strikeOut(i, hint);
		}		
	}
	final private void strikeOut(int step, long max){
		for (int i = step*2; i < max; i+=step) {
			sieve[i]=false;
		}
	}
		
	public Integer getNext() {
		if (last==sieve.length) {
			EOL();
			return null;
		}
		while(sieve[last] == false) {
			last++;
			if (last==sieve.length) {
				EOL();
				return null;
			}
		}
		return last++;
	}
}
